// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializableArrayOfT.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.IO
{
    using System;
    using System.IO;
    using System.IO.Compression;
    using System.Runtime.InteropServices;
    using System.Runtime.Serialization;

    /// <summary>
    /// Array representation that enables compact serialization by the DataContractSerializer
    /// Structs serialized this way must have the StructLayout(Sequential) annotation.
    /// </summary>
    /// <typeparam name="T">The type of struct to serialize. Must have the StructLayout(Sequential) annotation.</typeparam>
    [DataContract]
    public class SerializableArray<T> : SerializableArray
        where T : struct
    {
        /// <summary>
        /// Initializes a new instance of the SerializableArray class.
        /// </summary>
        /// <param name="noCompression">Determines whether to compress the array or not.</param>
        public SerializableArray(bool noCompression)
            : base(noCompression)
        {
        }

        /// <summary>
        /// Transforms the array into a compressed version, in preparation for compact serialization.
        /// </summary>
        /// <param name="array">The array to serialize.</param>
        public override void PrepareToSerialize(Array array)
        {
            this.Size = array.Length;
            T[] typedArray = (T[])array;
            GCHandle handle = GCHandle.Alloc(typedArray, GCHandleType.Pinned);

            try
            {
                int size = typedArray.Length * Marshal.SizeOf(typeof(T));
                this.Data = new byte[size];
                Marshal.Copy(handle.AddrOfPinnedObject(), this.Data, 0, size);
            }
            finally
            {
                handle.Free();
            }

            this.SerializationTransform();
        }

        /// <summary>
        /// Deserializes the original array from byte[] format.
        /// </summary>
        /// <returns>The deserialized array.</returns>
        public override Array GetTypedArray()
        {
            byte[] bytes;

            bytes = this.DeserializationTransform(Marshal.SizeOf(typeof(T)));
            T[] result = new T[this.Size];
            GCHandle handle = GCHandle.Alloc(result, GCHandleType.Pinned);

            try
            {
                Marshal.Copy(bytes, 0, handle.AddrOfPinnedObject(), bytes.Length);
            }
            finally
            {
                handle.Free();
            }

            return result;
        }
    }
}
